// Tstats['us']横线,   Tstats['time']竖线,  Tstats['path']path  ,Tstats['circle']小圆的位置
//vw svg的宽    vh svg的高
var svgstats = {us:[[5,5,0,100]],ci:100,time:[],path:['',''],circle:[[0,0],[0,0]],main:[[0,0,''],[0,0,'']],circler:2,linered:[0,0,0,0]},
	Klinestats = {us:[],ci:100,timeline:[],timetext:[],path:[''],main:[[0,0,''],[0,0,'']],circler:2,linered:[],make:[[0,0,0,true]]},
	Slinestats = {mathline:[],mathtext:[],dpath:'0',circle:[[0,0][0,0]],ty:[],test:[0,0],circle:[]},
	vw=$(window).width(),
	vh=vw*2/3;
//vph 实际的高, bpw 实际宽和时间长都比 按秒算,bph 实际高与点数差比 按点算
var vph=vh-20,bpw,bph;

var example2 = new Vue({
  el: '#example-2',
  data: {
    pageshow:0,//pageshow 下单 持仓 结算 显示
    monybalance:balance,//monybalance 页面余额
    points:0,//当前保留小数位数
    pointx:fluctuation,//当前波动范围
    svgshow:0,//svgshow 当前svg显示
    widthSize:320,//widthSize   svg宽
    activeheight:240,//activeheight    svg高
    showModal: false,//showModal 提示消息显示
    showModaltitle:'sssss',//showModaltitle 提示消息标题
    showModalbody:'',
    stats:nowx,//stats 交易数量数组
    statx:nos,//statx 触发止损数组
    tanchubox:false,//tanchubox 弹出显示
    tanchushow:0,//tanchushow 弹出当前填充 1买涨 0买跌
    tanchushowxs:false,//
    tanchuarr:[],//tanchuarr 弹出循环列表
    dianshu:[0,'0','0%',0,0,0,0,false,0,0,0],//点数数组
    svgstats:svgstats,//分时svg数组
    vbox:[vw,vh],//分时box
    lzstats:Klinestats,//蜡烛图 数组
    sdstats:Slinestats,//闪电
    kklls:true,//闪电记录开启
    kkllsarr:[],//闪电记录数组
    currency_unit:currency_unit,//货币单位
    exchange_rate:exchange_rate,//汇率
    surplus_value:nos.liss[nos.i],//止盈值
    surplus_valuex:(nos.liss[nos.i]*exchange_rate).toFixed(0),//止盈值 转换后
    stop_loss_margin:nos.lise[nos.i]*nowx.list[nowx.i],//止损保证金
    stop_loss_marginx:(nos.lise[nos.i]*nowx.list[nowx.i]*exchange_rate).toFixed(0),//止损保证金  转换后
    transaction_costmore:transaction_cost,//交易综合费初始值
    transaction_cost:transaction_cost*nowx.list[nowx.i],//交易综合费
    transaction_costx:(transaction_cost*exchange_rate).toFixed(0),//交易综合费  转换后
    transaction_heji:(transaction_cost+nos.lise[nos.i])*nowx.list[nowx.i],//合计支付
    transaction_hejix:((transaction_cost+nos.lise[nos.i])*nowx.list[nowx.i]*exchange_rate).toFixed(0),//合计支付  转换后
    holdarr:[[],0,0,false,0],//holdarr[0][0]方向holdarr[0][1]止损holdarr[0][2]止赢holdarr[0][3]买入点数holdarr[0][4]点数比率holdarr[0][5]持仓盈亏holdarr[1]持仓总盈亏
	settlement:[],//持仓数组
	settlementpage:1//持仓页码
  },
  methods: {
    say: function (event,i) {
    	//下单 持仓  结算   显示
    	this.tanchushow=parseInt(i);
//  	if(event==1){holdata()};
    	if(event==2){setlte(1)};
    	example2.pageshow=event;
    },
    clickp:function(el){
    	//交易数量数组  当前显示
    	this.stats.i=el;
//  	止损保证金变化
    	this.stop_loss_margin  = this.statx.lise[this.statx.i]*this.stats.list[this.stats.i];
    	this.stop_loss_marginx = (this.statx.lise[this.statx.i]*this.stats.list[this.stats.i]*this.exchange_rate).toFixed(example2.points);
//  	交易综合费变化
		this.transaction_cost = this.transaction_costmore*nowx.list[nowx.i];
		this.transaction_costx= ((this.transaction_costmore*nowx.list[nowx.i])*this.exchange_rate).toFixed(example2.points);
//		合计支付
		this.transaction_heji = (this.statx.lise[this.statx.i]+this.transaction_costmore)*this.stats.list[this.stats.i];
		this.transaction_hejix= ((this.statx.lise[this.statx.i]+this.transaction_costmore)*this.stats.list[this.stats.i]*this.exchange_rate).toFixed(example2.points);
    },
    clickx:function(el){
    	//触发止损数组  当前显示
    	this.statx.i=el;
    	this.surplus_valuex=(this.statx.liss[this.statx.i]*this.exchange_rate).toFixed(this.points);
//  	止损保证金变化
    	this.stop_loss_margin  = this.statx.lise[this.statx.i]*this.stats.list[this.stats.i];
    	this.stop_loss_marginx = (this.statx.lise[this.statx.i]*this.stats.list[this.stats.i]*this.exchange_rate).toFixed(example2.points);
		//止盈变化
		this.surplus_value=this.statx.liss[this.statx.i];
//		合计支付
		this.transaction_heji = (this.statx.lise[this.statx.i]+this.transaction_costmore)*this.stats.list[this.stats.i];
		this.transaction_hejix= ((this.statx.lise[this.statx.i]+this.transaction_costmore)*this.stats.list[this.stats.i]*this.exchange_rate).toFixed(example2.points);
    },
    tanchu:function(e){
    	//弹出点击事件
    	this.tanchubox = true ;
    	this.tanchushowxs= e;
    	if(e==0){
    		this.tanchuarr=nowx.list;
    	}else{
    		this.tanchuarr=nos.list;
    	}
    },
    tanchure:function(el){
    	//弹出列表点击返回
    	if(this.tanchushowxs==0){
    		this.stats.i=el;
    	}else{
    		this.statx.i=el;
    	}
    	//止损保证金变化
    	this.stop_loss_margin  = this.statx.lise[this.statx.i]*this.stats.list[this.stats.i];
    	this.stop_loss_marginx = (this.statx.lise[this.statx.i]*this.stats.list[this.stats.i]*this.exchange_rate).toFixed(example2.points);
		//止盈变化
		this.surplus_value=this.statx.liss[this.statx.i];
//  	交易综合费变化
		this.transaction_cost = this.transaction_costmore*nowx.list[nowx.i];
		this.transaction_costx= ((this.transaction_costmore*nowx.list[nowx.i])*this.exchange_rate).toFixed(example2.points);
//		合计支付
		this.transaction_heji = (this.statx.lise[this.statx.i]+this.transaction_costmore)*this.stats.list[this.stats.i];
		this.transaction_hejix= ((this.statx.lise[this.statx.i]+this.transaction_costmore)*this.stats.list[this.stats.i]*this.exchange_rate).toFixed(example2.points);
    	this.tanchubox=false;
    },
    buy:function(){
    	// 下单ajax
    	$.ajax({
				type:"post",
				url:urlgt,
				data:{
					option_id:option_id,
					direction:this.tanchushow,
					stop_loss_value:this.statx.list[this.statx.i],//止损
					surplus_value:this.surplus_value,//止盈
                    stop_loss_margin:this.stop_loss_margin,//止损保证金
					amount:this.transaction_heji,//合计支付
					hand_count:this.stats.list[this.stats.i],//交易手数
					transaction_cost:this.transaction_cost//交易综合费
				},
				dataType:"json",
				async:true,
				success:function(datas){
					if(datas.status==1){
                        holdata();
						example2.pageshow=1;
						example2.monybalance=datas.user.balance;
					}else if(datas.status==0){
						example2.showModal=true;
						example2.showModaltitle='下单提示';
						example2.showModalbody=datas.msg[0];
					};
				}
			});
    },
    cardholdclick:function(i,j){
    	//平仓
    	holdele(i,j);
    },
    cardholdone:function(){
    	//一键平仓
    	onepice();
    },
    moremore:function(){
//  	加载更多
		this.settlementpage+=1;
		setlte(this.settlementpage);
    },
    lightning:function(){
    	//闪电
    	this.svgshow=2;
    	kkllsx();
    }
  }
})

//分时图 组件
Vue.component('polygraph', {
props: ['stats'],
template: '#polygraph-template',
computed: {
	pois: function () {
      return this.stats
    },
    time:function(){
      return this.stats
    }
},
components: {}
})
//蜡烛 组件
Vue.component('polygratu', {
props: ['stats'],
template: '#polygraph-temprate',
computed: {
	pois: function () {
      return this.stats
    },
    time:function(){
      return this.stats
    }
},
components: {}
})

Vue.component('polygratgg', {
props: ['stats'],
template: '#polygraph-tem',
computed: {
	pois: function () {
      return this.stats
    },
    time:function(){
      return this.stats
    }
},
components: {}
})

Vue.component('modal', {
	template: '#modal-template'
})

window.onload=function(){
	$('.footerBox').remove();
	$('.MaskZpai').remove();
	$('#example-2').show();
	holdata();
	//保留位数计算
	var pointstring=(String(fluctuation)).split('.');
	if(pointstring.length==1){example2.points=0;}else{example2.points=pointstring[1].length}
	//svg大小
	example2.widthSize=$(window).width();
	example2.activeheight=$(window).width()*2/3;
	//点数刷新
	setInterval(function(){
		$.getJSON(urltime, function(data){
				var k=[ data.last_price,
						(parseFloat(data.last_price)-data.open_price).toFixed(example2.points),
						((parseFloat(data.last_price)-data.open_price)/data.open_price*100).toFixed(2)+'%',
						(data.sell_amount>70?70:data.sell_amount),
						data.sell_amount,
						(data.buy_amount>70?70:data.buy_amount),
						data.buy_amount,
						(parseFloat(data.last_price)>parseFloat(data.open_price)?true:false),
						data.sell_price,
						data.buy_price,
						example2.tanchushow==0?data.buy_price:data.sell_price,
						data.volume,
						data.price2,
						data.price3,
						data.open_price,
						data.high_price,
						data.low_price,
						data.low_price
					]
			    example2.dianshu=k;
			});
	},800);
	//分时背景加载
	var olddata=[];
	timemath();

	setInterval(function(){
		kline()
	},60000);
	//分时数据
	kline();
	function kline(){
		$.getJSON(urls,function(result){
			pathkline(result)
		})
	}


	klinepath()
}

function timemath(){
	//时间长度计算
	$.map(timetest, function(val,i) {
		var timeho=parseInt(val.substr(0,2)),timeht=parseInt(val.substr(6,2)),
			timeso=parseInt(val.substr(3,2)),timest=parseInt(val.substr(9,2));
		timelang+=(timeht-timeho)*60+timest-timeso;
	});
	bpw=vw/timelang;
	//时间间隔比率
	var p1=((parseInt((timetest[0]).substr(6,2))-parseInt((timetest[0]).substr(0,2)))*60+parseInt((timetest[0]).substr(9,2))-parseInt((timetest[0]).substr(3,2)))/timelang,
		p2=(( parseInt(timetest[timetest.length-1].substr(6,2)) - parseInt(timetest[timetest.length-1].substr(0,2)) )*60 + parseInt(timetest[timetest.length-1].substr(9,2)) - parseInt(timetest[timetest.length-1].substr(3,2)) )/timelang;
	//竖线数组
	var ul=[[1,1,0,vph,(timetest[0]).substr(0,5),1,vph+12],
			[vw*p1-13,vw*p1-13,0,vph,(timetest[0]).substr(6,5),vw*p1-26,vph+12],
			[vw*p2-13,vw*p2-13,0,vph,(timetest[timetest.length-1]).substr(0,5),vw*p2-26,vph+12],
			[vw-1,vw-1,0,vph,(timetest[timetest.length-1]).substr(6,5),vw-30,vph+12]
		   ]
	svgstats['time']=ul;
	//横线数组
	var dlarray=[];
	for (var i=0;i<6;i++) {
		var dl=[0,vw,(vph/6*(i+1)),vph/6*(i+1)]
		dlarray.push(dl);
	}
	svgstats['us'] =dlarray;
}
//持仓列表   持仓数据刷新
//holdarr[0]方向
//holdarr[1]止损
//holdarr[2]止赢
//holdarr[3]买入点数
//holdarr[4]最小波动价格
//holdarr[5]持仓盈亏
//holdarr[6]订单id
//holdarr[7]止损点数
//holdarr[8]止赢点数
//holdarr[9]
var close_time;
function holdata(){
	$.ajax({
		type:"get",
		url:positionurl,
		async:true,
		success:function(eeee){
			var neb=[],j;
			$.map(eeee, function(val,i) {
				var nob=[val.direction==1?'买涨':'买跌',val.stop_loss_value,val.surplus_value,parseFloat(val.buy_point),fluctuation_price,0,val.id,parseFloat(val.stop_loss_point),parseFloat(val.surplus_point),true];
                neb.push(nob);
				j=i;
				close_time=val.close_time;
			});
//			console.log(eeee)
			Vue.set(example2.holdarr, 0, neb);
			example2.holdarr[3]=true;
			piontadd(close_time);
		}
	});
}
//持仓列表   持仓额度刷新
var piontadds=true;
function piontadd(valtime){
var now_time=Date.parse(new Date())/1000;
	if(piontadds){
		setInterval(function(){
			var momomo=0,j,k=false,now_time=new Date(),now_time_hour=now_time.getHours(),now_time_minutes=now_time.getMinutes();
			if(parseInt(now_time)>parseInt(valtime)){
				example2.holdarr[0].splice(0);
			}else{
				$.map(example2.holdarr[0], function(val,i) {
					var changes=0;
					if(val[0]=='买涨'){
						if(parseFloat(example2.dianshu[0])>=parseFloat(val[8]) || parseFloat(example2.dianshu[0])<= parseFloat(val[7])){
							example2.holdarr[0].splice(i,1);
                            changes=0;
//                          console.log('1');
						}else{
							changes=(parseFloat(example2.dianshu[0])-parseFloat(val[3]))*parseFloat(val[4])/parseFloat(fluctuation);
						}
					}else{
						if(parseFloat(example2.dianshu[0])<=parseFloat(val[8]) || parseFloat(example2.dianshu[0])>=parseFloat(val[7])){
							example2.holdarr[0].splice(i,1);
                            changes=0;
//                          console.log('0')
						}else{
							changes=(parseFloat(val[3])-parseFloat(example2.dianshu[0]))*parseFloat(val[4])/parseFloat(fluctuation);
						}
					};
					momomo+=changes;
					example2.holdarr[0][i][5]=changes;
					j=i;
				});
				if(j>=0){
					example2.holdarr[4]=j+1;
				}else{
					example2.holdarr[4]=0;
				}
				if(isNaN(momomo)){
					example2.holdarr[1]=0;
				}else{
					example2.holdarr[1]=momomo;
				}
			}
		},800)
		piontadds=false;
	}
}
//验证是否清除
function holdele(el,i){
	console.log(el+'/'+i)
	$.ajax({
		type:"post",
		url:unwindorderurl,
		async:true,
		data:{id:el,'_token':_token},
		success:function(elem){
			if(elem.status==1){
				example2.holdarr[0].splice(i,1);
				example2.showModaltitle='平仓提示';
				example2.showModalbody='平仓成功';
				example2.showModal=true;
				example2.monybalance=elem.user.balance;
			}else if(elem.status==0){
				holdata()
			};
		}
	});
}
//一键平仓
function onepice(){
	$.ajax({
		type:"post",
		url:unwindorderallurl,
		async:true,
		data:{option_id:option_id,'_token':_token},
		success:function(elem){
			if(elem.status==1){
				example2.holdarr[0].splice(0);
				example2.showModaltitle='平仓提示';
				example2.showModalbody='平仓成功';
				example2.showModal=true;
				example2.monybalance=elem.user.balance;
			}else if(elem.status==0){
				holdata()
			};
		}
	});
}
//结算
function setlte(elp){
	$.ajax({
		type:"post",
		url:settlementurl,
		async:true,
		data:{page:elp,'_token':_token},
		success:function(elem){
			if(elp==1){
				example2.settlement=elem.orders.data;
			}else{
				var opl=example2.settlement;
				$.map(elem.orders.data, function(val,i) {
					opl.push(val);
				});
				example2.settlement=opl;
			}
		}
	});
}


//日K AJAX
function klinepath(){
	$.ajax({
		type:"get",
		url:datekurl,
		async:true,
		dataType:'json',
		data:{'_token':_token},
		success:function(elem){
			elem=(elem.splice(0,20)).reverse();
			klinepathdele(elem)
		}
	});
}
//日K path
function klinepathdele(elem){
	var linepatharr=new Array(),
		patharr	   =new Array(),
		depharr	   =new Array(),
		minpath=parseFloat(elem[0]['Open']),maxline=parseFloat(elem[0]['Volume']),
		num,maxpath=parseFloat(elem[0]['Open']),jj;
	//竖线位置
	for(var i=0;i<5;i++){
		var timelineone=[vw/4*i,vw/4*i,0,vph*0.7],timelinetwo;
		example2.lzstats['timeline'].push(timelineone);
	};
	//时间计算
	for(var i=0;i<4;i++){
		if(i==0){
			timelinetwo=[vw/4*i,vph*0.7+10,(elem[0]['Date']).substring(5,10)];
		}else{
			timelinetwo=[vw/4*i-15,vph*0.7+10,(elem[(i+1)*5-1]['Date']).substring(5,10)];
		}
		example2.lzstats['timetext'].push(timelinetwo);
	};
	//横线位置
	for(var i=0;i<8;i++){
		var timelineone=[0,vw,vph*0.7/7*i,vph*0.7/7*i];
		example2.lzstats['us'].push(timelineone);
	};
	$.map(elem, function(val,i) {
		maxpath=maxpath>parseFloat(val['Open']) ?maxpath:parseFloat(val['Open']);
		maxpath=maxpath>parseFloat(val['Close'])?maxpath:parseFloat(val['Close']);
		maxpath=maxpath>parseFloat(val['High']) ?maxpath:parseFloat(val['High']);
		maxpath=maxpath>parseFloat(val['Low'])  ?maxpath:parseFloat(val['Low']);

		minpath=minpath<parseFloat(val['Open'])  ? minpath:parseFloat(val['Open']);
		minpath=minpath<parseFloat(val['Close']) ? minpath:parseFloat(val['Close']);
		minpath=minpath<parseFloat(val['High'])  ? minpath:parseFloat(val['High']);
		minpath=minpath<parseFloat(val['Low'])   ? minpath:parseFloat(val['Low']);

		maxline=maxline>parseFloat(val['Volume']) ? maxline: parseFloat(val['Volume']);
	});

	example2.lzstats['main']=[[vw-35,10,maxpath],[vw-35,vph*0.7-5,minpath]];
	num=vw*0.75/20,jj=(maxpath-minpath)/(vph*0.7);
	$.map(elem, function(val,i) {
		var henline=[i*num,i*num,vph*0.7-(parseFloat(val['High'])-minpath)/jj,vph*0.7-(parseFloat(val['Low'])-minpath)/jj];
		var M0=i*num-(num/2-1),M1=i*num+(num/2-1),L1=vph*0.7-(parseFloat(val['Open'])-minpath)/jj,L2=vph*0.7-(parseFloat(val['Close'])-minpath)/jj;
		var mvto;
		if(i==0){mvto='M'+2.5+','+L1+'L'+2.5+','+L1+'L'+2.5+','+L2+'L'+2.5+','+L2+'L'+2.5+','+L1+'Z';}else{mvto='M'+M0+','+L1+'L'+M1+','+L1+'L'+M1+','+L2+'L'+M0+','+L2+'L'+M0+','+L1+'Z';}
		var deph;
		if(maxline==0){deph=[i*num,i*num,vph,vph-1];}else{deph=[i*num,i*num,vph,vph-vph*0.19*parseFloat(val['Volume'])/maxline]};
		if(val['Close']>val['Open']){linepatharr.push([henline,true]);patharr.push([mvto,true]);depharr.push([deph,true,num]);};
		if(val['Open']>val['Close']){linepatharr.push([henline,false]);patharr.push([mvto,false]);depharr.push([deph,false,num])};
	});
	example2.lzstats['linered']=linepatharr;
	example2.lzstats['path']=patharr;
	example2.lzstats['make']=depharr;
}
//line 图
//pathmaxdata K线path最大值, pathmindata K线path最小值, last最后一个值
function pathkline(olddata){
	var pathmaxdata,pathmindata,last;
	pathmaxdata=parseFloat(olddata[0]['TimeTrend']);
	pathmindata=parseFloat(olddata[0]['TimeTrend']);

	$.map(olddata, function(val,i) {
		pathmaxdata= pathmaxdata>parseFloat(val['TimeTrend']) ? pathmaxdata : parseFloat(val['TimeTrend']);
		pathmindata= pathmindata<parseFloat(val['TimeTrend']) ? pathmindata : parseFloat(val['TimeTrend']);
	});
	svgstats['main']=[[vw-40,15,pathmaxdata],[vw-40,vph-5,pathmindata]];
	var jj=pathmaxdata-pathmindata;
	if(pathmaxdata<15){
		jj+=50;
	}
	var datap1,datap2;
	datap1='M 0,'+vph;
	$.map(olddata,function(val,i){
		var bod=vph-(parseFloat(val['TimeTrend'])-pathmindata)*vph/jj;
		last=[(i+1)*bpw,bod];
		datap1+="L"+(i+1)*bpw+","+bod;
	});
	datap2=datap1+"L"+olddata.length*bpw+","+vph +"L"+0+","+vph +"Z";
	svgstats['path']=[datap2,datap1];
	svgstats['circle']=[last,last];
	svgstats['linered']=[0,vw,last[1],last[1]];

}
//闪电
function dleo(){
	var timearr=  new Array(),
		textarr=  new Array();
	for(var i=0;i<7;i++){
		var timelineone=[0,vw,vph/6*i,vph/6*i],timelinetwo;
		if(i==0){
			timelinetwo=[vw-50,+10];
		}else{
			timelinetwo=[vw-50,vph/6*i+3];
		};
		timearr.push(timelineone)
		textarr.push(timelinetwo)
	}
	example2.sdstats['mathline']=timearr;
	example2.sdstats['mathtext']=textarr;
}
//闪电
var clickgo=parseFloat(example2.dianshu[0]),op=[];
function kkllsx(){
	clickgo=parseFloat(example2.dianshu[0]);
	op=[];
	if(example2.kklls){
		dleo();
		setInterval(function(){
			var datap1='M 0,'+vph*0.5;
			if(parseFloat(example2.dianshu[0])>(clickgo+example2.pointx*3*2) || parseFloat(example2.dianshu[0])<(clickgo-example2.pointx*3*2)){
				kkllsx();
			}else{
				op.push(parseFloat(example2.dianshu[0]));
				example2.kkllsarr=op;
				example2.kkllsarr.reverse();
				example2.kkllsarr.splice(110);
				example2.kkllsarr.reverse();
			}
			var bod
			$.map(example2.kkllsarr,function(val,i){
					bod=vph*0.5-(val-clickgo)*vph/example2.pointx/12;
					datap1+="L"+(i+1)*vw*0.7/100+","+bod;
					example2.kkllsarr=[];
					example2.sdstats['mathtext'][0][2]=(clickgo+example2.pointx*3*2).toFixed(example2.points);
					example2.sdstats['mathtext'][1][2]=(clickgo+example2.pointx*2*2).toFixed(example2.points);
					example2.sdstats['mathtext'][2][2]=(clickgo+example2.pointx*2).toFixed(example2.points);
					example2.sdstats['mathtext'][3][2]=(clickgo).toFixed(example2.points);
					example2.sdstats['mathtext'][4][2]=(clickgo-example2.pointx*2).toFixed(example2.points);
					example2.sdstats['mathtext'][5][2]=(clickgo-example2.pointx*2*2).toFixed(example2.points);
					example2.sdstats['mathtext'][6][2]=(clickgo-example2.pointx*3*2).toFixed(example2.points);
			});
			var datap2=datap1+"L"+(vw-15)+","+bod;
			example2.sdstats['test']=[vw-50,bod,op[op.length-1]];
			example2.sdstats['dpath']=datap2;
			example2.sdstats['circle']=[(op.length-1)*vw*0.7/100,bod];
		},800)
	};
	example2.kklls=false;
}
